<template>
	<div class="home-product-list">
		<!-- 顶部搜索栏 -->
		<div class="search-container">
			<van-search v-model="searchValue" :show-action="true" action-text="搜索" placeholder="搜索商品"
				@search="onSearch" />
		</div>
		<!-- 加载状态 -->
		<div v-if="isLoading" class="loading-container">
			<van-loading type="spinner" size="large" />
			<p class="loading-text">正在加载商品...</p>
		</div>

		<!-- 空状态 -->
		<van-empty v-else-if="!productList.length" description="暂无匹配商品" image="empty" />

		<!-- 商品列表 -->
		<div v-else class="goods-list">
			<div class="goods-item" v-for="item in filteredList" :key="item.id" @click=""
				:class="{ 'out-of-stock': !item.stock }">
				<!-- 商品图片区域 -->
				<div class="goods-image-container">
					<van-image :src="`${apiDomainName}${item.pic}`" :error-src="errorImage" class="goods-image"
						fit="cover" />
				</div>

				<!-- 商品信息区域 -->
				<div class="goods-info">
					<div class="goods-title van-ellipsis">{{ item.title }}</div>

					<!-- 评分和销量 -->
					<div class="rating-sales">
						<van-rate v-model="item.rating" readonly size="14" color="#ff9f00" void-color="#e0e0e0" />
						<span class="sales-count">月售 {{ item.soldCount || generateRandomSales() }}</span>
					</div>

					<div class="spec van-ellipsis">{{ item.spec || '暂无规格信息' }}</div>

					<!-- 价格区域 -->
					<div class="price-container">
						<div class="price">￥{{ formatPrice(item.price) }}</div>
						<div v-if="item.originalPrice" class="original-price">￥{{ formatPrice(item.originalPrice) }}
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 加载更多 -->
		<van-load-more :status="loadMoreStatus" @loadmore="onLoadMore" />
	</div>
</template>

<script>
	import {
		getProductListAPI
	} from "@/api/product.js";

	export default {
		data() {
			return {
				productList: [],
				apiDomainName: "",
				errorImage: 'https://picsum.photos/300/300?text=图片加载失败',
				isLoading: false,
				activeTab: 0,
				searchValue: '',
				page: 1,
				pageSize: 10,
				loadMoreStatus: 'more',
				filters: {
					category: 'all',
					sort: 'default'
				}
			};
		},
		created() {
			this.fetchProductList();
		},
		computed: {
			// 过滤和搜索后的商品列表
			filteredList() {
				let list = [...this.productList];

				// 搜索过滤
				if (this.searchValue) {
					const keyword = this.searchValue.toLowerCase();
					list = list.filter(item =>
						item.title.toLowerCase().includes(keyword) ||
						(item.spec && item.spec.toLowerCase().includes(keyword))
					);
				}

				// 分类过滤
				if (this.filters.category && this.filters.category !== 'all') {
					list = list.filter(item => item.category === this.filters.category);
				}

				// 排序
				if (this.filters.sort === 'price-asc') {
					list.sort((a, b) => a.price - b.price);
				} else if (this.filters.sort === 'price-desc') {
					list.sort((a, b) => b.price - a.price);
				} else if (this.filters.sort === 'sales') {
					list.sort((a, b) => (b.soldCount || 0) - (a.soldCount || 0));
				}

				return list;
			}
		},
		methods: {
			async fetchProductList(reset = false) {
				if (reset) {
					this.page = 1;
					this.loadMoreStatus = 'more';
				}

				this.isLoading = true;

				try {
					const result = await getProductListAPI({
						page: this.page,
						pageSize: this.pageSize,
						category: this.activeTab === 0 ? null : ['hot', 'new', 'discount'][this.activeTab - 1]
					});

					const newProducts = result.data || [];

					if (reset) {
						this.productList = newProducts;
					} else {
						this.productList = [...this.productList, ...newProducts];
					}

					// 判断是否还有更多数据
					if (newProducts.length < this.pageSize) {
						this.loadMoreStatus = 'noMore';
					} else {
						this.page++;
					}
				} catch (error) {
					console.error('获取商品列表失败:', error);
					this.$toast.fail('获取商品列表失败');
					this.loadMoreStatus = 'error';
				} finally {
					this.isLoading = false;
				}
			},
			generateRandomSales() {
				// 生成10到999之间的随机整数
				return Math.floor(Math.random() * 550) + 10;
			},
			formatPrice(price) {
				return price.toFixed(2);
			},

			onTabChange(index) {
				this.activeTab = index;
				this.fetchProductList(true);
			},

			onSearch() {
				this.fetchProductList(true);
			},

			onLoadMore() {
				if (this.loadMoreStatus === 'loading' || this.loadMoreStatus === 'noMore') return;
				this.fetchProductList();
			},
		}
	};
</script>

<style scoped>
	/* 使用Tailwind CSS配置主题 */
	@layer utilities {
		.content-auto {
			content-visibility: auto;
		}

		.scrollbar-hide {
			-ms-overflow-style: none;
			scrollbar-width: none;
		}

		.scrollbar-hide::-webkit-scrollbar {
			display: none;
		}

		.text-shadow {
			text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
		}

		.card-hover {
			transition: all 0.3s ease;
		}

		.card-hover:hover {
			transform: translateY(-4px);
			box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
		}
	}

	/* 基础样式 */
	.home-product-list {
		background-color: #fff;
		min-height: 100vh;
	}

	.search-container {
		padding: 12px 16px;
		background-color: #fff;
	}

	.goods-list {
		padding: 12px 16px;
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.goods-item {
		display: flex;
		background-color: #fff;
		border-radius: 16px;
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.10);
		overflow: hidden;
		position: relative;
		transition: all 0.2s ease;
	}

	.goods-item.out-of-stock {
		opacity: 1;
	}

	.goods-image-container {
		flex: 0 0 120px;
		height: 120px;
		position: relative;
	}

	.goods-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.goods-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		padding: 12px 16px;
		justify-content: space-between;
	}

	.goods-title {
		font-size: 16px;
		font-weight: 500;
		color: #333;
		line-height: 1.4;
		margin-bottom: 6px;
	}

	.rating-sales {
		display: flex;
		align-items: center;
		margin-bottom: 4px;
	}

	.sales-count {
		font-size: 12px;
		color: #666;
		margin-left: 8px;
	}

	.spec {
		font-size: 13px;
		color: #666;
		margin-bottom: 8px;
	}

	.price-container {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.price {
		font-size: 18px;
		font-weight: bold;
		color: #e53935;
	}

	.original-price {
		font-size: 12px;
		color: #999;
		text-decoration: line-through;
		margin-left: 8px;
	}

	.add-to-cart {
		padding: 0 10px !important;
		height: 28px !important;
		line-height: 28px !important;
		border-radius: 14px !important;
	}

	.discount-badge {
		position: absolute;
		top: 8px;
		left: 8px;
		background-color: #e53935;
		color: white;
		font-size: 12px;
		font-weight: 500;
		padding: 2px 6px;
		border-radius: 4px;
		z-index: 10;
	}

	.sold-out-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.4);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 20;
	}

	.sold-out-overlay span {
		color: white;
		font-size: 16px;
		font-weight: bold;
		background-color: rgba(0, 0, 0, 0.6);
		padding: 4px 12px;
		border-radius: 4px;
	}

	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 40px 0;
	}

	.loading-text {
		margin-top: 16px;
		font-size: 14px;
		color: #666;
	}
</style>